var log4js = require('log4js');
var path = require('path');
var _ = require('underscore');
var util = require('util');
var config = require('./config');

var schedulelogs = null;
var access = null;
var errorlog = null;

var log4jsInit = function(){
    log4js.configure({
        appenders: [
            { type: 'console' }, //控制台输出
            {
                type: 'file', //文件输出
                filename:  path.join(config.logPath, 'access.log'),
                maxLogSize: 10240,
                backups:3,
                category: 'access'
            },
            {
                type: "file",
                filename: path.join(config.logPath, 'schedule.log'),
                pattern: "yyyy-MM-dd",
                alwaysIncludePattern: false,
                category: 'schedule'
            },
            {
                type: "file",
                filename: path.join(config.logPath, 'schedule_error.log'),
                pattern: "yyyy-MM-dd",
                alwaysIncludePattern: false,
                category: 'schedule_error'
            }
        ],
        replaceConsole: true
    });

    schedulelogs = log4js.getLogger('schedule');
    access = log4js.getLogger('access');
    errorlog = log4js.getLogger('schedule_error');
    schedulelogs.setLevel('INFO');
    access.setLevel('INFO');
    errorlog.setLevel('ERROR');

};


var originalConsoleFunctions = {
	log		:	function(){schedulelogs.debug.apply(schedulelogs, arguments);},
	info	:	function(){schedulelogs.info.apply(schedulelogs, arguments);},
	error	:	function(){errorlog.error.apply(errorlog, arguments);},
	warn	:	function(){schedulelogs.warn.apply(schedulelogs, arguments);},
	trace	:	function(){schedulelogs.trace.apply(schedulelogs, arguments);},
	fatal	:	function(){schedulelogs.fatal.apply(schedulelogs, arguments);}
};

var restoreConsole = function() {
	_.each(originalConsoleFunctions, function(fun, key){
		console[key] = fun;
	});
};
exports.init = function(){
    log4jsInit();
    restoreConsole();
};

exports.access = function(){
	return access;
};